/**
 * 在线拍照
 */
package com.stone.capPhoto;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.stone.common.service.FileService;
import com.stone.para.IConstant;
import com.stone.sys.pojo.TUser;

import frm.ssh.dao.BaseDAO;

import java.text.SimpleDateFormat;
import java.util.*;
/**
 * @author kevin cheng
 *
 */
public class onLineTakePhotoServlet extends HttpServlet {
	private static final long serialVersionUID = 1354876191194195586L;
	
	@Autowired 
	private BaseDAO baseDAO;
	@Autowired 
    public void init(ServletConfig config) throws ServletException {  
    	super.init();
    	ServletContext servletContext = config.getServletContext();
    	super.init();     
         
        WebApplicationContext webApplicationContext = WebApplicationContextUtils  
                .getWebApplicationContext(servletContext);  
        AutowireCapableBeanFactory autowireCapableBeanFactory = webApplicationContext  
                .getAutowireCapableBeanFactory();  
//        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,  
//                config.getServletContext()); 
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(config.getServletContext());
        autowireCapableBeanFactory.configureBean(this, "fileService");  
    }  
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)    
	throws ServletException, IOException {    
	processRequest(request, response);    
	}    
	  
	public void doPost(HttpServletRequest request, HttpServletResponse response)    
	 throws ServletException, IOException {    
	processRequest(request, response);    
	}    
	
	public void processRequest(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {
		String sbid = request.getParameter("sbid");
		response.setContentType("text/html;charset=UTF-8");   
        response.setHeader("Pragma", "No-cache");   
        response.setHeader("Cache-Control", "no-cache");   
        response.setDateHeader("Expires", 0);   
  
        String bitmap_data = request.getParameter("bitmap_data");   
        int width = Integer.parseInt(request.getParameter("width"));   
        int height = Integer.parseInt(request.getParameter("height"));   
        BufferedImage img = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);   
		try {   
            int w = width;   
            int h = height;   
            int[] pixels = new int[w * h];   
            String[] m_tempPics = bitmap_data.split(",");   
            for (int x = 0; x < w; x++) {   
                for (int y = 0; y < h; y++) {   
                    long pic_argb = (long) Long.parseLong(m_tempPics[x * h + y]);   
                    int a = (int) (pic_argb >> 24 & 0xFF);   
                    int r = (int) (pic_argb >> 16 & 0xFF);   
                    int g = (int) (pic_argb >> 8 & 0xFF);   
                    int b = (int) (pic_argb & 0xFF);   
                    pixels[y * w + x] = new Color(r, g, b, a).getRGB();   
                }   
            }   
            img.setRGB(0, 0, w, h, pixels, 0, w);   
            img.flush();   
            ByteArrayOutputStream bao = new ByteArrayOutputStream();   
            ImageIO.write(img, "jpg", bao);   
            byte[] data = bao.toByteArray();  
            String filePath = request.getRealPath("/") + "upload/equipment_photo";
            
            File upDir = new File(filePath);
            if (!upDir.exists())
            {
                upDir.mkdirs();
            }
            
            String saveName = UUID.randomUUID().toString(); ;
            String fileName = saveName + ".jpg";
            
          //写图片
            File f = new File(filePath+"\\" + fileName);
    		DataOutputStream dos = new DataOutputStream(new FileOutputStream(f));
    		dos.write(data);
    		dos.flush();
    		dos.close();
    		
            String url = "<a href=\"/DLPLANMIS/upload/equipment_photo/" + fileName + "\" target=\"_blank\"><img src=\"/DLPLANMIS/upload/equipment_photo/"+fileName+"\" width=\"320\" height=\"210\"></a>";
            Calendar cal = new GregorianCalendar();
    		SimpleDateFormat r = new SimpleDateFormat("yyyy-MM-dd");
			String sql = "INSERT INTO tab_file VALUES(seq_file.nextval, "
						+ " '" + fileName + "',"
						+ " '" + fileName + "',"
						+ " '" + url + "',"
						+ sbid + ","
						+ " 'TAB_EQUIPMENT_PHOTO',"
						+ " to_date('"+r.format(cal.getTime())+"', 'yyyy-MM-dd'),"
						+ " '" + ((TUser) request.getSession().getAttribute(
								IConstant.SESSION_TUSER)).getId() + "', "
						+ " '1')";
			System.out.println("======SQL======" + sql);
						
			baseDAO.insertBySql(sql);
            
    		response.setContentType("text/xml");   
            response.getWriter().write("/uploads/photo/" + fileName);   
        }
        catch(Exception ex)
        {
        	response.setContentType("text/xml");   
            response.getWriter().write("图片保存失败"); 
            ex.printStackTrace();
        }
	}

	/**
	 * @return the baseDAO
	 */
	public BaseDAO getBaseDAO() {
		return baseDAO;
	}

	/**
	 * @param baseDAO the baseDAO to set
	 */
	public void setBaseDAO(BaseDAO baseDAO) {
		this.baseDAO = baseDAO;
	}
}
